package org.firstspringdema.thread;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

@Service
public class AsyncService {
    // 简单的异步任务
    @Async
    public void asyncTask() {
        System.out.println("异步任务执行中,线程名:" + Thread.currentThread().getName());
        // 模拟耗时操作
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // 中断线程
        }
        System.out.println("异步任务执行完成");
    }

    // 带返回值的异步方法
    @Async
    public CompletableFuture<String> asyncTask2() {
        System.out.println("带返回值的异步任务执行,线程名:" + Thread.currentThread().getName());
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return CompletableFuture.failedFuture(e);
        }
        return CompletableFuture.completedFuture("异步返回结果");

    }

}
